package cn.shadow.account.service.impl;

import cn.shadow.account.infrastructure.storage.account.dao.AccountMapper;
import cn.shadow.account.infrastructure.storage.account.entity.Account;
import cn.shadow.account.model.DeductDto;
import cn.shadow.account.service.IAccountService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

/**
 * @author 冯啸迪
 */
@Service
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int insertAccount() {
        Account account = new Account();
        account.setCustomerCode("test");
        account.setBalance(new BigDecimal(0));
        account.setFreezeBalance(new BigDecimal(0));
        account.setIsDelete((byte)0);
        account.setCreateTime(new Date());
        account.setUpdateTime(new Date());
        return accountMapper.insert(account);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @GlobalTransactional(rollbackFor = RuntimeException.class)
    @Override
    public int deductBalance(DeductDto deductDto) {
        Random random = new Random();
        Boolean flag = random.nextBoolean();
        if (flag) {
            throw new RuntimeException("测试数据");
        }
        Account account = accountMapper.selectByPrimaryKey(deductDto.getId());
        Account record = new Account();
        record.setId(account.getId());
        BigDecimal newBalance = account.getBalance().subtract(deductDto.getAmount());
        record.setBalance(newBalance);
        record.setFreezeBalance(deductDto.getAmount());
        return accountMapper.updateByPrimaryKeySelective(record);
    }
}
